package org.colafries.admin.querybuilder.customQuery;

import org.apache.logging.log4j.util.Strings;
import org.colafries.admin.entity.vo.CustomQueryReqVO;
import org.colafries.admin.exceptions.ServiceException;
import org.colafries.admin.exceptions.enums.ErrorCodeEnum;
import org.colafries.admin.querybuilder.entity.CustomQueryParamContext;
import org.colafries.admin.querybuilder.entity.CustomQuerySqlBuildContext;
import org.colafries.admin.entity.domain.QueryParam;
import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author colafries
 * @version v1.0
 * @ClassName FilterBuilder
 * @Description
 * @date Created in 2024/5/16
 **/
public class CustomQueryFilterBuilder implements CustomQuerySqlSegmentBuilder {
    @Override
    public void buildQueryParma(CustomQueryReqVO.CustomQueryParam customQueryParam, CustomQueryParamContext customQueryParamContext) {
        // Filters
        Optional.ofNullable(customQueryParam)
                .map(CustomQueryReqVO.CustomQueryParam::getFilters)
                .ifPresent(filters -> {
                    filters.forEach(filter -> {
                        QueryParam.Filter queryFilter = new QueryParam.Filter();
                        BeanUtils.copyProperties(filter, queryFilter);
                        customQueryParamContext.getFilters().add(queryFilter);
                    });
                });
    }

    @Override
    public void buildQuery(QueryParam queryParam, CustomQuerySqlBuildContext customQuerySqlQueryContext) {
        // filters
        List<QueryParam.Filter> filters = Optional.of(queryParam).map(QueryParam::getFilters)
                .orElse(Collections.emptyList());

        //having
        for (QueryParam.Filter filter : filters) {
            String expression = customQuerySqlQueryContext.getColumnExpressionMap().get(filter.getFieldHash());
            if (Strings.isEmpty(expression)) {
                throw new ServiceException(ErrorCodeEnum.GL999999, "Filter过滤表达式获取失败");
            }
            customQuerySqlQueryContext.getHavingConditions().add(String.format("%s %s %s", expression, filter.getOperator(), filter.getValue()));
        }

    }
}
